package ru.spb.osll.myfit.ssh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.InteractiveCallback;
import ch.ethz.ssh2.Session;

public class SSHClientManager {

  private Connection connection;
  private String myHost;
  private User myUser;
  private boolean isActive;

  public SSHClientManager(String host, User user) throws Exception {
    myHost = host;
    myUser = user;
    initializeConnection();
    isActive = true;
  }

  private void initializeConnection() throws Exception {
    connection = new Connection(myHost);
    try {
      connection.connect();
    } catch (IOException e) {
      throw new Exception("can't connect to host " + myHost, e);
    }
    connection.authenticateWithKeyboardInteractive(myUser.getLogin(),
        new InteractiveCallback() {

          @Override
          public String[] replyToChallenge(String name, String instruction,
                                           int numPrompts, String[] prompt,
                                           boolean[] echo) throws Exception {
            
            if (numPrompts == 1) {
              return new String[] {myUser.getPassword()};
            }else{
              return new String[numPrompts];
            }
          }
        });
  }

  public List<String> executeCommand(String command) throws Exception {
    Session session = null;
    List<String> response = new LinkedList<String>();
    try {
      session = connection.openSession();
      session.execCommand(command);
      session.getStdout();
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          session.getStdout()));
      String line;
      while ((line = reader.readLine()) != null) {
        response.add(line);
      }
    } catch (IOException e) {
      if (session != null) {
        session.close();
      }
      throw new Exception("execution of command \"" + command + "\" is failed", e);
    }
    return response;
  }

  public void close() {
    if (connection != null) {
      connection.close();
    }
    isActive = false;
  }
  
  public boolean isActive(){
    return isActive;
  }
}
